package com.lagou.edu.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.lagou.edu.common.status.ResultStatus;
import com.lagou.edu.dao.AuthCodeDao;
import com.lagou.edu.entity.AuthCode;
import com.lagou.edu.fegin.IEmailServiceClient;
import com.lagou.edu.service.IAuthCodeService;
import com.lagou.edu.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * @author 赵虎
 * @date 2021/2/18 2:31 下午
 */
@Slf4j
@Service
public class IAuthCodeServiceImpl implements IAuthCodeService {

    @Autowired
    private AuthCodeDao authCodeDao;

    // 有效期  单位为  秒
    @Value("${config.code.validate.expire}")
    private int codeExpireSeconds;

    @Autowired
    private IEmailServiceClient iEmailServiceClient;


    @Override
    public void createCode(String email) {
        String code = RandomUtil.randomNumbers(6);

        long createTime = System.currentTimeMillis();
        long expireTime = createTime + codeExpireSeconds * 1000L;

        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        authCode.setCreatetime(new Date(createTime));
        authCode.setExpiretime(new Date(expireTime));
        authCodeDao.save(authCode);
        log.info("邮箱和验证码---->{},{}", email, code);
        iEmailServiceClient.sendMail(email, code);
    }

    @Override
    public ResultVO validateAuthCode(String email, String code) {
        AuthCode latest = authCodeDao.findFirstByEmailOrderByIdDesc(email);
        if (Objects.isNull(latest)) {
            return ResultVO.fail(ResultStatus.ERROR_REQUEST, "这个邮箱没有验证码");
        }
        if (!latest.getCode().equalsIgnoreCase(code)) {
            return ResultVO.fail(ResultStatus.ERROR_SYSTEM, "验证码不正确");
        }
        long expireTime = latest.getExpiretime().getTime();
        if (expireTime <= System.currentTimeMillis()) {
            return ResultVO.fail(ResultStatus.ERROR_SYSTEM, "验证码已过期");
        }

        return ResultVO.ok();
    }
}
